using System.Collections.Generic;
using UnityEngine;

public class RelicBoardView : MonoBehaviour
{
    [Header("数据")]
    public List<Relic> relics = new();
    public List<RelicView> relicViews = new();

    [Header("显示设置")]
    [SerializeField] private Transform slot;          // 第一个位置
    [SerializeField] private float spacing = 100f;    // 每个 relicView 间距

    /// <summary>
    /// 初始化显示（清空再批量添加）
    /// </summary>
    public void Setup(List<Relic> newRelics)
    {
        ClearAll();
        foreach (var relic in newRelics)
        {
            AddRelic(relic, false); // 批量添加，不立即重排
        }
        RepositionViews(); // 最后一次性重排
    }

    /// <summary>
    /// 增加一个 relic
    /// </summary>
    public void AddRelic(Relic relic, bool reposition = true)
    {
        relics.Add(relic);

        if (relic is BagItemData data)
        {
            var newView = BagItemViewCreator.Instance.CreateView(data, this.gameObject);
            if (newView is RelicView view)
                relicViews.Add(view);
        }

        if (reposition)
            RepositionViews();
    }

    /// <summary>
    /// 删除一个 relic
    /// </summary>
    public void RemoveRelic(Relic relic, bool reposition = true)
    {
        // 通过索引匹配 relic 和 relicView，保持一一对应
        int index = relics.IndexOf(relic);
        if (index >= 0 && index < relicViews.Count)
        {
            var view = relicViews[index];
            if (view != null)
                Destroy(view.gameObject);

            relics.RemoveAt(index);
            relicViews.RemoveAt(index);

            if (reposition)
                RepositionViews();
        }
    }

    /// <summary>
    /// 清空所有 relic
    /// </summary>
    private void ClearAll()
    {
        foreach (var rv in relicViews)
        {
            if (rv != null)
                Destroy(rv.gameObject);
        }
        relicViews.Clear();
        relics.Clear();
    }

    /// <summary>
    /// 重新排列 relicViews（使用本地坐标，无动画）
    /// </summary>
    private void RepositionViews()
    {
        if (slot == null) return;

        for (int i = 0; i < relicViews.Count; i++)
        {
            var view = relicViews[i];
            if (view != null)
            {
                Vector3 targetPos = slot.localPosition + Vector3.right * spacing * i;
                view.transform.localPosition = targetPos; // 直接赋值
            }
        }
    }
}
